package com.sport.websocket;

import com.google.gson.Gson;
import com.sport.constant.WsResultConstant;
import com.sport.pojo.vo.SendingMessage;
import com.sport.pojo.vo.WsResult;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/wsend/{id}/{room}")
@Component
public class WsEnd {
    private static final Map<String, Session> onlineUsers = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam("id")String id, @PathParam("room")String room) {
        //1，将session进行保存
        onlineUsers.put(id+"&"+room,session);
    }
    public void broadcast(String roomId ,String UandR){
        try {
            //遍历map集合
            Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
            System.out.println(entries.size());
            for (Map.Entry<String, Session> entry : entries) {
                if(isConRoom(entry.getKey(),roomId)) {
                    Session session = entry.getValue();
                    //发送消息
                    session.getBasicRemote().sendText(UandR);
                }
            }
        }catch (Exception e) {
            //记录日志
        }
    }
    public boolean isConId(String key,String id){
        if(key.substring(0,key.indexOf("&")).equals(id)){
            return true;
        }
        return false;
    }
    public boolean isConRoom(String key,String room){
        if(key.substring(key.indexOf("&")+1).equals(room)){
            return true;
        }
        return false;
    }
    @OnMessage
    public void onMessage(String message) {
        try {
            SendingMessage msg = new Gson().fromJson(message, SendingMessage.class);
            String s = new Gson().toJson(new WsResult(WsResultConstant.ADD_MESSAGE,"增加的消息", msg.getMessage()));
            broadcast(msg.getRoomId(),s);
        } catch (Exception e) {
        }
    }
    @OnClose
    public void onClose(Session session,@PathParam("id")String id,@PathParam("room")String room) {
        //1,从onlineUsers中剔除当前用户的session对象
        onlineUsers.remove(id+"&"+room);
        System.out.println(id+"-"+room+"下线");
    }
}
